package com.bupt.kgplatform.controller.docker;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bupt.kgplatform.Util.R;
import com.bupt.kgplatform.entity.DataCleanTask;
import com.bupt.kgplatform.entity.http.AllDataCleanTask;
import com.bupt.kgplatform.mapper.DataCleanTaskMapper;
import com.bupt.kgplatform.service.DataCleanTaskService;
import com.bupt.kgplatform.service.DockerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

/**
 * DockerController
 *
 * @author zrz
 * @date 2023/5/26
 * @time 16:35
 * @Description docker
 */

@RestController
@RequiredArgsConstructor
@RequestMapping("/datacleantask" )
@Api(value = "datacleantask", tags = "数据清洗任务")
public class DataCleanTaskController {

    private final DataCleanTaskService dataCleanTaskService;
    private final DockerService dockerService;

    @Autowired(required = false)
    private final DataCleanTaskMapper dataCleanTaskMapper;

    @Value("${host.ip}")
    public String ip;

    @PostMapping("/add")
    public R startDocker(@RequestBody DataCleanTask dataCleanTask){


//        dataCleanTaskService.save(dataCleanTask);
//        DataCleanTask byId = dataCleanTaskService.getById(id);
        int port = dockerService.getPort();

        if (port == 0){ // 创建容器失败
            return R.failure("不能再创建更多的任务了");
        }
        else {
            R containers = dockerService.createContainers(dataCleanTask.getId(), port);

            if (containers.getCode() == 1){  //docker创建成功
                dataCleanTask.setPort(port);
                dataCleanTask.setDockerState("success");
                dataCleanTask.setCleanState("failed");
                dataCleanTaskService.save(dataCleanTask);
                return R.ok("http://" + ip + ":" + String.valueOf(port));
            }
            else {  //docker创建失败
                return containers;
            }

        }
    }

    @ApiOperation(value = "通过id删除", notes = "通过id删除")
    @DeleteMapping("/{id}" )
    public R removeById(@PathVariable String id) {
        int i = dockerService.checkContainer(id);//检查该任务附属的docker任务的是否正在运行中
        if (i == 1){
            return R.failure("请先关闭该任务的docker之后再删除任务");
        }
        else{ // 没问题的话再删除
            R r = dockerService.deleteContainer(id);  //先删容器，再删任务
            return R.ok(dataCleanTaskService.removeById(id));
        }

    }

    @GetMapping("/getAll")
    public R getAll(){
        AllDataCleanTask allDataCleanTask = new AllDataCleanTask();

        allDataCleanTask.setData(dataCleanTaskMapper.selectList(null));
        allDataCleanTask.setTotal(dataCleanTaskMapper.countByIdIsNotNull());
        return R.ok(allDataCleanTask);
    }


}
